<template>
  <view>
    
  </view>
</template>

<script>
export default {
  data() {
    return {
      messages: []
    }
  },
  mounted() {
    this.startSSE()
  },
  methods: {
    startSSE() {
      uni.request({
        url: this.baseUrl + '/sse/connect/'+ uni.getStorageSync('userId'),
        method: 'GET',
        header: {
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
          // 'Connection': 'keep-alive'
        },
        success: (res) => {
          this.handleSSE(res)
        },
        fail: (err) => {
          console.error(err)
        }
      })
    },
    handleSSE(res) {
      const eventSource = new EventSource(res.header['x-sse-url'])

      eventSource.addEventListener('message', (event) => {
        const data = JSON.parse(event.data)
        // this.messages.push(data)
				this.$emit('onMessage',data)
				
      })

      eventSource.addEventListener('error', (error) => {
        console.error('SSE Error:', error)
      })
    }
  }
}
</script>